from flask import blueprints, render_template, request, jsonify
from flask_login import login_required, current_user

import SparkApi
from config import appid
from config import api_secret
from config import api_key
from config import domain
from config import Spark_url

bp = blueprints.Blueprint('xiaoCheng', __name__, url_prefix='/xiaoCheng')

#初始上下文内容，当前可传system、user、assistant 等角色
text = [
    {"role": "user", "content": "你叫小橙助手，你的职责是为大学生解决学习过程中的难题，当学生提出问题时，回答尽可能让学生懂"},  # 用户的历史问题
    {"role": "user", "content": "你的名字叫小橙助手"},  # 用户的历史问题
    {"role": "user", "content": "不要出现'科大讯飞'这几个字"},  # 用户的历史问题
    {"role": "user", "content": "不要继续回答上一个问题"},  # 用户的历史问题
]


def getText(role, content):
    jsoncon = {}
    jsoncon["role"] = role
    jsoncon["content"] = content
    text.append(jsoncon)
    return text


def getlength(text):
    length = 0
    for content in text:
        temp = content["content"]
        leng = len(temp)
        length += leng
    return length


def checklen(text):
    while (getlength(text) > 8000):
        del text[0]
    return text


@bp.route('/chat', methods=['GET', 'POST'])
@login_required
def chat():
    if request.method == 'POST':
        user_message = request.json.get('message')
        # print(user_message)

        question = checklen(getText("user", user_message))
        SparkApi.answer = ""
        SparkApi.main(appid, api_key, api_secret, Spark_url, domain, question)

        return jsonify({"code": 200, 'data':SparkApi.answer, "msg": "succes"})
    return render_template('chat.html', user_name=current_user.username, email=current_user.email)
